<template>
  <body>
  <h2>泡芙英语单词 独立教师版</h2>
  <div class="header-wrapper">
    <i class="fa-regular fa-headphones"></i>
    <span @click="showCustomerService = true">联系客服</span>
  </div>
  <div class="container" :class="{ 'right-panel-active': isSignUp }">
    <!-- 注册 -->
    <div class="form-container sign sign-up-container">
      <form @submit.prevent="handleSignUp">
        <h1>Create Account</h1>
        <div class="social-container">
          <a @click="loginLabel = 'Phone'"><i class="fa-solid fa-phone"/></a>
        </div>
        <span>registration can only use phone number</span>
        <InputField v-model="signUpForm.nickname" type="text" label="Nickname"/>
        <InputField v-model="signUpForm.phone" type="text" label="Phone"/>
        <InputField v-model="signUpForm.password" type="password" label="Password"/>
        <button type="submit" :disabled="isSigningUp">
          <!-- 注册按钮加载状态 -->
          <template v-if="isSigningUp">
            <LoadingSpinner size="16px" color="#fff" borderWidth="2px"/>
          </template>
          <template v-else>注 册</template>
        </button>
        <p style="cursor: pointer" @click="isSignUp = false">去登录</p>
      </form>
    </div>

    <!-- 登录 -->
    <div class="form-container sign-in-container">
      <form @submit.prevent="handleSignIn">
        <h1>Sign in</h1>
        <div class="social-container">
          <a @click="loginLabel = 'Email'"><i class="fa-solid fa-envelope"/></a>
          <a @click="loginLabel = 'Phone'"><i class="fa-solid fa-phone"/></a>
          <a @click="loginLabel = 'Account'"><i class="fa-solid fa-user"/></a>
        </div>
        <span>mail, phone or account three can be used</span>
        <InputField v-model="signInForm.credential" :type="loginLabel" :label="loginLabel"/>
        <InputField v-model="signInForm.password" type="password" label="Password"/>
        <a @click="showCustomerService = true">Forgot your password?</a>
        <button type="submit" :disabled="isSigningIn">
          <!-- 登录按钮加载状态 -->
          <template v-if="isSigningIn">
            <LoadingSpinner size="16px" color="#fff" border-width="2px"/>
          </template>
          <template v-else>登 录</template>
        </button>
        <p style="cursor: pointer" @click="isSignUp = true">注册账户</p>
      </form>
    </div>

    <!-- Overlay -->
    <div class="overlay-container">
      <div class="overlay">
        <div class="overlay-panel overlay-left"/>
        <div class="overlay-panel overlay-right"/>
      </div>
    </div>
  </div>

  <footer>
    <p>
      <a :href="baseDomain" target="_blank">泡芙工作室</a>
    </p>
  </footer>

  <phone-verify-dialog
    v-if="dialogVisible"
    :visible.sync="dialogVisible"
    :preferred-sim="signUpForm.phone"
    sms-number="15528052586"
    message-text="手机号验证"
    @openHelp="showCustomerService=true"
  />

  <!-- 客服对话框组件 -->
  <CustomerServiceDialog
    v-if="showCustomerService"
    :visible.sync="showCustomerService"
  />
  </body>
</template>

<script>

import InputField from '@/views/component/InputField.vue'
import LoadingSpinner from '@/views/component/LoadingSpinner.vue' // 引入加载组件
import { register, verifyCanRegister } from '@/api/user'
import { getPublicKey } from '@/api/commonApi'
import RsaUtil from '@/utils/rsa-util'
import PhoneVerifyDialog from '@/views/component/PhoneVerifyDialog.vue'
import CustomerServiceDialog from '@/views/component/CustomerServiceDialog.vue'

export default {
  name: 'LoginSignup',
  components: {
    CustomerServiceDialog,
    PhoneVerifyDialog,
    InputField,
    LoadingSpinner // 注册组件
  },
  created() {
    getPublicKey().then(res => {
      this.publicKey = res
    })
  },
  data() {
    return {
      // 控制客服对话框显示/隐藏
      showCustomerService: false,
      dialogVisible: false,
      publicKey: '',
      baseDomain: process.env.VUE_APP_FILE_PORT,
      loginLabel: 'Phone',
      isSignUp: false,
      // 新增加载状态变量
      isSigningIn: false,  // 登录加载状态
      isSigningUp: false,  // 注册加载状态
      signInForm: {
        credential: '', // 凭据 邮箱、账户、电话号码
        password: ''
      },
      signUpForm: {
        nickname: '',
        phone: '',
        password: ''
      },
      errors: {
        credential: '',
        nickname: '',
        phone: '',
        password: ''
      }
    }
  },
  methods: {
    async handleSignIn() {
      if (this.validateLoginForm()) {
        // 开始登录 - 显示加载状态
        this.isSigningIn = true
        try {
          const rsa = new RsaUtil(this.publicKey)
          const params = {
            password: rsa.encrypt(this.signInForm.password)
          }
          let method = ''
          if (this.loginLabel === 'Phone') {
            params.phone = rsa.encrypt(this.signInForm.credential)
            method = 'phone'
          } else if (this.loginLabel === 'Email') {
            params.email = rsa.encrypt(this.signInForm.credential)
            method = 'email'
          } else {
            params.account = rsa.encrypt(this.signInForm.credential)
            method = 'account'
          }
          params.method = method
          await this.$store.dispatch('user/login', params)
          this.$router.push({ path: '/' })
        } catch (error) {
          // 登录失败处理（保持原逻辑）
        } finally {
          // 结束登录 - 隐藏加载状态
          this.isSigningIn = false
        }
      } else {
        // 表单验证失败处理
        for (const key in this.errors) {
          if (this.errors[key]) {
            this.$notify.error({
              title: '输入检查不通过',
              showClose: false,
              message: this.errors[key]
            })
            break
          }
        }
      }
    },
    async handleSignUp() {
      if (this.validateForm()) {
        // 开始注册 - 显示加载状态
        this.isSigningUp = true
        try {
          const rsa = new RsaUtil(this.publicKey)
          const params = {
            nickname: this.signUpForm.nickname,
            phone: rsa.encrypt(this.signUpForm.phone),
            password: rsa.encrypt(this.signUpForm.password)
          }

          // 请求服务器验证
          const res = await verifyCanRegister(params)
          if (!res) {
            this.$notify.error({
              title: '请求结果',
              showClose: false,
              message: '请验证手机号'
            })
            this.dialogVisible = true
            return
          }

          // 注册请求
          await register(params)
          this.$notify.success({
            title: '请求结果',
            showClose: false,
            message: '注册成功'
          })
          this.$router.push('/')
        } catch (error) {
          // 注册失败处理
        } finally {
          // 结束注册 - 隐藏加载状态
          this.isSigningUp = false
        }
      } else {
        // 表单验证失败处理
        for (const key in this.errors) {
          if (this.errors[key]) {
            this.$notify.error({
              title: '输入检查不通过',
              showClose: false,
              message: this.errors[key]
            })
            break
          }
        }
      }
    },
    // 手机号正则验证
    isMobile(phone) {
      return /^1[3-9]\d{9}$/.test(phone)
    },
    // 登录表单校验
    validateLoginForm() {
      // 保持原逻辑不变
      let valid = true
      if (!this.signInForm.credential.trim()) {
        this.errors.credential = '登录凭据必填！'
        valid = false
      } else if (this.loginLabel === 'Phone' && !this.isMobile(this.signInForm.credential)) {
        this.errors.credential = '手机号格式错误，仅支持中国大陆手机号！'
        valid = false
      } else {
        this.errors.credential = ''
      }

      const pwd = this.signInForm.password.trim()
      const pattern = /^[a-zA-Z0-9!@#$%^&*()_\-+=\[{\]};:'",.<>/?\\|]{6,20}$/
      if (!pwd.trim()) {
        this.errors.password = '密码为必填参数！'
        valid = false
      } else if (!pattern.test(pwd)) {
        this.errors.password = '密码格式错误，仅支持6-20位数字、英文字符以及常见英文标点！'
        valid = false
      } else {
        this.errors.password = ''
      }

      return valid
    },
    // 注册表单校验
    validateForm() {
      // 保持原逻辑不变
      let valid = true
      if (!this.signUpForm.nickname.trim()) {
        this.errors.nickname = '昵称为必填参数！'
        valid = false
      } else {
        this.errors.nickname = ''
      }

      if (!this.signUpForm.phone.trim()) {
        this.errors.phone = '手机号为必填参数！'
        valid = false
      } else if (!this.isMobile(this.signUpForm.phone)) {
        this.errors.phone = '手机号格式错误，仅支持中国大陆手机号！'
        valid = false
      } else {
        this.errors.phone = ''
      }

      const pwd = this.signUpForm.password
      if (!pwd.trim()) {
        this.errors.password = '密码为必填参数！'
        valid = false
      } else if (pwd.length < 6 || pwd.length > 20) {
        this.errors.password = '密码格式错误，仅支持6-20位！'
        valid = false
      } else {
        this.errors.password = ''
      }

      return valid
    }
  }
}
</script>

<style scoped>
* {
  box-sizing: border-box;
}

body {
  background: #0e1110;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  font-family: 'Montserrat', sans-serif;
  height: 100vh;
  margin: -20px 0 50px;
}

h1 {
  font-weight: bold;
  margin: 0;
}

h2, h3 {
  text-align: center;
  color: #ffffff;
}

p {
  font-size: 14px;
  line-height: 20px;
  letter-spacing: 0.5px;
  margin: 20px 0 30px;
}

span {
  font-size: 12px;
}

a {
  color: #333;
  font-size: 14px;
  text-decoration: none;
  margin: 15px 0;
}

button {
  border-radius: 20px;
  border: 1px solid #0e1110;
  background-color: #0e1110;
  color: #ffffff;
  font-size: 12px;
  font-weight: bold;
  padding: 12px 45px;
  letter-spacing: 1px;
  text-transform: uppercase;
  transition: transform 80ms ease-in;
}

button:active {
  transform: scale(0.95);
}

button:focus {
  outline: none;
}

form {
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 0 50px;
  height: 100%;
  text-align: center;
}

input {
  background-color: #eee;
  border: none;
  padding: 12px 15px;
  margin: 8px 0;
  width: 100%;
}

.container {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
  position: relative;
  overflow: hidden;
  width: 768px;
  max-width: 100%;
  min-height: 480px;
}

.form-container {
  position: absolute;
  top: 0;
  height: 100%;
  transition: all 0.6s ease-in-out;
}

.sign-in-container {
  left: 0;
  width: 50%;
  z-index: 2;
}

.container.right-panel-active .sign-in-container {
  transform: translateX(100%);
}

.sign-up-container {
  left: 0;
  width: 50%;
  opacity: 0;
  z-index: 1;
}

.container.right-panel-active .sign-up-container {
  transform: translateX(100%);
  opacity: 1;
  z-index: 5;
  animation: show 0.6s;
}

@keyframes show {

  0%,
  49.99% {
    opacity: 0;
    z-index: 1;
  }

  50%,
  100% {
    opacity: 1;
    z-index: 5;
  }
}

.overlay-container {
  position: absolute;
  top: 0;
  left: 50%;
  width: 50%;
  height: 100%;
  overflow: hidden;
  transition: transform 0.6s ease-in-out;
  z-index: 100;
}

.container.right-panel-active .overlay-container {
  transform: translateX(-100%);
}

.overlay {
  background: #0e1110;
  background: -webkit-linear-gradient(to right, #0e1110, #0e1110);
  background: linear-gradient(to right, #0e1110, #0e1110);
  background-repeat: no-repeat;
  background-position: center -50px;
  background-image: url(../../assets/gradient.png);
  color: #ffffff;
  position: relative;
  left: -100%;
  height: 100%;
  width: 200%;
  transform: translateX(0);
  transition: transform 0.6s ease-in-out;
}

.container.right-panel-active .overlay {
  transform: translateX(50%);
}

.overlay-panel {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  text-align: center;
  top: 0;
  height: 100%;
  width: 50%;
  transform: translateX(0);
  transition: transform 0.6s ease-in-out;
}

.overlay-left {
  transform: translateX(-20%);
  background-image: url(../../assets/ellie.png);
  background-position: center top;
  background-size: cover;
  color: #42c3b8;

  p {
    font-weight: bold;
  }
}

.container.right-panel-active .overlay-left {
  transform: translateX(0);
}

.overlay-right {
  right: 0;
  transform: translateX(0);
  background-image: url(../../assets/joe.png);
  background-position: center top;
  background-size: cover;
  color: #fb8c37;

  p {
    font-weight: bold;
  }
}

.container.right-panel-active .overlay-right {
  transform: translateX(20%);
}

.social-container {
  margin: 20px 0;
}

.social-container a {
  border: 1px solid #dddddd;
  border-radius: 50%;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin: 0 5px;
  height: 40px;
  width: 40px;
}

footer {
  background-color: #0e1110;
  color: #fff;
  font-size: 14px;
  bottom: 0;
  position: fixed;
  left: 0;
  right: 0;
  text-align: center;
  z-index: 999;
}

footer p {
  margin: 10px 0;
}

footer i {
  color: red;
}

footer a {
  color: #ffffff;
  text-decoration: none;
}

.header-wrapper {
  display: flex;
  justify-content: right;
  align-items: center; /* 垂直居中对齐 */
  width: 768px; /* 和 container 宽度一致，或者 100% 自适应 */
  max-width: 100%;
  color: #ffffff;
  cursor: pointer;
  padding: 5px 5px;
}
</style>
